<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Visit\Action;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 *
 * @Controller
 */
class VisitClientList extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientContract
     */
    protected $clientService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/dashboard/visit/clientList", methods="GET")
     */
    public function handle(): array
    {
        $user = user();
        if (empty($user)) {
            throw new CommonException(ErrorCode::AUTH_UNAUTHORIZED, '登入异常请重新登入');
        }
        // 校验参数
        $params = $this->request->all();
        $orderBy = isset($params['orderBy']) ? json_decode($params['orderBy'], true) : [];
        $list = Db::table('work_employee as employee')
            ->when(isset($params['employeeId']) && is_numeric($params['employeeId']), function ($query) use ($params) {
                $query->where('employee.id', $params['employeeId']);
            })
            ->when(isset($params['deptId']) && !empty($params['deptId']), function ($query) use ($params) {
                $query->where('dept.id', '=',$params['deptId']);
            })
            ->when(!empty($orderBy), function ($query) use ($orderBy) {
                foreach ($orderBy as $key => $item) {
                    $query->orderBy($key, str_replace('end', '', $item));
                }
            })
            ->leftJoin('work_department as dept', 'employee.main_department_id', '=', 'dept.id')
            ->join('client as client', 'client.work_employee_id', 'employee.id')
            ->leftJoin('call_record as record', 'client.id', '=', 'record.client_id')
            ->where('record.call_duration', '>', 0)
            ->where('record.call_type', '=', "out")
            ->groupBy(['employee.id'])
            ->select([
                'employee.id',
                'employee.name',
                'dept.name as deptName',
                Db::raw("COUNT(DISTINCT mc_client.id) as clientCount"),
                Db::raw("COUNT(DISTINCT mc_record.destination_number) as callCount"),
                Db::raw("TRUNCATE(COUNT(DISTINCT mc_record.destination_number)/COUNT(DISTINCT mc_client.id),4) as rate")
            ])->paginate();
        $list || $list = collect([]);
        $list = $list->toArray();
        if (!empty($list['data'])) {
            foreach ($list['data'] as &$item) {
                $item->rate = $item->rate ? bcmul($item->rate, '100', 2) . '%' : "0%";
            }
            unset($item);
        }

        $total = Db::table('work_employee as employee')
            ->when(isset($params['employeeId']) && is_numeric($params['employeeId']), function ($query) use ($params) {
                $query->where('employee.id', $params['employeeId']);
            })
            ->when(isset($params['deptId']) && !empty($params['deptId']), function ($query) use ($params) {
                $query->where('dept.name', '=' . $params['deptId']);
            })
            ->leftJoin('work_department as dept', 'employee.main_department_id', '=', 'dept.id')
            ->join('client as client', 'client.work_employee_id', 'employee.id')
            ->leftJoin('call_record as record', 'client.id', '=', 'record.client_id')
            ->where('record.call_duration', '>', 0)
            ->where('record.call_type', '=', "out")
            ->select([
                Db::raw("COUNT(DISTINCT mc_client.id) as clientCount"),
                Db::raw("COUNT(DISTINCT mc_record.destination_number) as callCount"),
                Db::raw("TRUNCATE(COUNT(DISTINCT mc_record.destination_number)/COUNT(DISTINCT mc_client.id),4) as rate")
            ])->first();
        $list['totalRate']=$total->rate? bcmul($total->rate, '100', 2) . '%' : "0%";
        $list['totalCallCount']=$total->callCount??0;
        $list['totalClientCount']=$total->clientCount??0;

        return $list;
    }
}

